package com.handong.handserialprogram.utils;

import com.google.gson.Gson;
import com.handong.handserialprogram.model.bean.TagCoordinateModel;

import cn.pda.serialport.Tools;

/**
 * 检查串口工具类
 */
public class CheckUtil {

    /**
     * 检验串口传上来的数据是否完整
     *
     * @param data
     * @return
     */
    /*public static byte u8CheckSum8Calibration(byte[] data) {

        short checkSum = 0x00;
        int len = data.length-1;
        for (int i = 0; i < len; i++) {
            checkSum += data[i];
        }
       // return (byte) (checkSum & 0xFF);
        return (byte)(checkSum & 0xFF);
    }*/
    public static byte u8CheckSum8Calibration(byte[] data) {
        byte checkSum = 0;
        int len = data.length-1;
        for (int i = 0; i < len; i++) {
            checkSum ^= data[i];
        }
        return (byte) (checkSum & 0xFF);
    }
    /**
     * 得到16进制的命令。
     *
     * @param cmd
     * @return
     */
    public static byte[] checkSum8Caculation(String cmd) {

        byte[] cmdData = Tools.HexString2Bytes(cmd);

        byte checkByte = 0;
        int len = cmdData.length;
        for (int i = 0; i < len; i++) {
            checkByte ^= cmdData[i];
        }
        //byte checkByte = (byte) ((~checkSum + 1) & 0xFF);
        byte[] newCmd = new byte[len + 3];
        newCmd[len+1]=0x0d;
        newCmd[len+2]=0x0a;
        System.arraycopy(cmdData, 0, newCmd, 0, len);
        newCmd[len] = checkByte;
        JLog.d("SerialPortUtil", "Check sum:" + Tools.byteToHexString(newCmd));
        return newCmd;
    }


    public byte[] objectToHexArray(TagCoordinateModel model) {
        Gson gson = new Gson();
        String data = gson.toJson(model);
        byte[] dataArray = Tools.hexStringToByteArray(data);
        int len = dataArray.length;
        byte[] result = new byte[len + 10];
        byte[] dataLength = Tools.hexString2Bytes(Integer.toHexString(len));
        for (int i = 3; i >= 0; i--) {

        }
        return null;
    }

    /**
     * 实测距离 厘米转米 （精度为分米）  int转float  保留小数点后一位。
     *
     * @param dis
     * @return
     */
    public static float floatRoundToInt(int dis) {
        float tempFloat = (float) dis / 10;
        int tempInt = Math.round(tempFloat);
        return (float) tempInt / 10;
    }

    /**
     * 字节转大小 单位为M
     * @param size
     * @return
     */
    public static String formatDataSize(long size) {
        String ret = "";
        if (size < (1024 * 1024)) {
            ret = String.format("%dK", size / 1024);
        } else {
            ret = String.format("%.1fM", size / (1024 * 1024.0));
        }
        return ret;
    }
}
